<script setup lang='ts' name="upload-order">
import type { UploadInstance } from 'element-plus'

import { useGetAgreementProductExcel, useJcOrderMetaImportProduct } from '@fl/api/purchase'

const emits = defineEmits(['importSuccess'])
const agreementId = defineModel('agreementId')
const visible = defineModel<boolean>('visible')
const { mutate: DownLoadMutate } = useGetAgreementProductExcel()
const { isPending, mutate: ImportProducMutate } = useJcOrderMetaImportProduct()
const uploadRef = ref<UploadInstance>()
async function uploadFile(uploadFile) {
    // 创建 FormData 对象
    const param = new FormData()
    param.append('file', uploadFile.file)
    const params = {
        id: agreementId.value,
        param,
    }
    ImportProducMutate((params as any), {
        onSuccess: (res: any) => {
            emits('importSuccess', res)
        },
    })
}

function close() {
    visible.value = false
}

function downLoad() {
    DownLoadMutate(String(agreementId.value), {
        onSuccess: (res: any) => {
            const objectUrl = URL.createObjectURL(res)
            location.href = objectUrl
            URL.revokeObjectURL(objectUrl)
        },
    })
}

function beforeUpload(file: any) {
    const fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
    const typeList = ['xlsx']
    if (!typeList.includes(fileType)) {
        ElMessage.error('文件类型不符合')
        return false
    }
}
</script>

<template>
    <el-dialog v-model="visible"
               width="600"
               :close-on-click-modal="false"
               title="导入商品"
               @close="close"
    >
        <p class="guide">
            请下载商品清单后,删除不需要下单的商品,并重新上传
            <span class="text-#6eaff9 cursor-pointer"
                  @click="downLoad"
            >
                下载清单
            </span>
        </p>

        <div class="flex gap-10 justify-center">
            <el-button @click="close">
                取消
            </el-button>

            <ElUpload ref="uploadRef"
                      :show-file-list="false"
                      :http-request="uploadFile"
                      accept=".xlsx"
                      :before-upload="beforeUpload"
            >
                <template #trigger>
                    <ElButton type="primary"
                              :loading="isPending"
                    >
                        上传商品清单
                    </ElButton>
                </template>
            </ElUpload>
        </div>
    </el-dialog>
</template>

<style lang="less" scoped>
.guide {
    text-align: center;
    padding: 20px 0;
}
</style>
